package com.example.list.kunkun;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.list.R;
import com.example.utils.SharedPreferencesUtil;
import com.example.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 */
public class KunKunActivity extends AppCompatActivity {

    private RecyclerView rl_kun;
    private List<Integer> arrayList;
    MyAdapterKun adapter;
    private ArrayList<Integer> positionList = new ArrayList<Integer>();

    public  MediaPlayer mediaPlayer;
    private TextView tv_time;
    public static final int what_time=0x1;
    public static final int what_stop=0x2;
    public static final int what_end=0x3;
    public   int limitTime=20;
    private boolean hasStart;
    int currentScore;
    int bestScore;
    private KunDialog kunDialog;
    GridLayoutManager layoutManager;
    private SoundPool spool;
    int id_tap;
    int id_err;
    int id_end;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case what_time:
                    hasStart=true;
                    tv_time.setText("TIME:"+(--limitTime));
//                    时间为0.结束程序
                    if (limitTime==0) {
                        tv_time.setText("时间到!");
//                      要先弹出dialog，禁止点击后，再播放音乐
//                      否则极端情况下，音乐播放后，还可以再点击一下
                        showScore(what_end);
                        playVoice(id_end);
                    }
                    if (limitTime>0) {
                        handler.sendEmptyMessageDelayed(what_time,1000);
                    }else {
                        handler.sendEmptyMessage(what_end);
                    }
                    break;
                case what_stop:
                case what_end:
                    handler.removeCallbacksAndMessages(null);
                    showScore(msg.what);
                    break;
            }

        }
    };
    public  void showScore(int what){
        currentScore=positionList==null?0:positionList.size();
        bestScore= SharedPreferencesUtil.getInstance(KunKunActivity.this).getInt("score",0);
        if (currentScore>bestScore) {
            bestScore=currentScore;
            SharedPreferencesUtil.getInstance(KunKunActivity.this).saveInt("score",bestScore);
        }
        switch (what) {
            case what_stop:
                kunDialog.setTile("鸡你太美");
                break;
            case what_end:
                kunDialog.setTile("鸡你太太美");
                break;

        }
        kunDialog.setScore(currentScore,bestScore);
        kunDialog.show();
        kunDialog.setOnCanlceListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                kunDialog.dismiss();
                resetValue();
            }
        });
        kunDialog.setOnSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                kunDialog.dismiss();
            }
        });


    }

    private void resetValue() {
        limitTime=20;
        hasStart=false;
        tv_time.setText("TIME:"+limitTime);
        initData();
        adapter.setDatas(arrayList);
        adapter.notifyDataSetChanged();
        positionList.clear();

        layoutManager.scrollToPositionWithOffset(0, 0);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kun_kun);
        rl_kun = (RecyclerView) findViewById(R.id.kun_rl);
        tv_time = (TextView) findViewById(R.id.tv_time_kun);
        kunDialog = new KunDialog(KunKunActivity.this);


        initData();
        initSoundpool();
        //单一布局
        adapter = new MyAdapterKun(this, arrayList);
        layoutManager = new GridLayoutManager(this, 4);
//      666,一个设置将所有居于顶部的设计和计算，改为居于底部的
        layoutManager.setReverseLayout(true);
        rl_kun.setLayoutManager(layoutManager);

        rl_kun.setAdapter(adapter);
        adapter.setOnItemClickListener(new MyAdapterKun.ItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {

                if (!isClickAble(position)) {
                    ToastUtil.showToast("点击区域有误");
                    return;
                }

                //整除4，说明程序正常运行，
                //刷新篮球
//                播放音乐
                if (arrayList.get(position) % 4 == 0) {
                    positionList.add(position);
                    adapter.setPositinList(positionList);
                    playVoice(id_tap);

                    if (!hasStart) {
                        handler.sendEmptyMessage(what_time);
                    }
                } else {
//                  点击到其他区域，即是错误区域
                    dealClickError(position, view);
                    playVoice(id_err);

                    if (hasStart) {
                        handler.sendEmptyMessage(what_stop);
                    }
                }
                if (positionList.size()>1) {

                    layoutManager.scrollToPositionWithOffset((positionList.size()-1)*4, 0);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (hasStart) {
            SharedPreferencesUtil.getInstance(KunKunActivity.this).saveInt("limitTime",limitTime+1);
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasStart) {
          limitTime= SharedPreferencesUtil.getInstance(KunKunActivity.this).getInt("limitTime",0);
          handler.sendEmptyMessage(what_time);
        }
    }

    boolean isClickAble(int currentPosition){
//       获取当前点击行数
        int line = arrayList.get(currentPosition) / 4;
//        只能点击当前和下一行，其他都是错误区域
        int boundary;
        if (arrayList.get(currentPosition) %4==0) {
            boundary=positionList.size()+1;
        }else {
            boundary=positionList.size();
        }

        if ( line <= boundary) {
            //优化已点击位置，不可再次点击
            if (positionList.size()>=1) {
                if (positionList.get(positionList.size()-1)==currentPosition) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 点击错误区域，报错处理
     * @param position
     * @param view
     */
    private void dealClickError(int position, View view) {

        ImageView imageView = (ImageView)view.findViewById(R.id.img_kun);

        imageView.setImageResource(R.drawable.android_red);


    }
    void playVoice(int res){
//        if (mediaPlayer != null ) {
//            if (mediaPlayer.isPlaying()) {
//                mediaPlayer.release();
//            }
//            mediaPlayer = MediaPlayer.create(KunKunActivity.this, res);
//            mediaPlayer.start();
//        }else {
//            mediaPlayer = MediaPlayer.create(KunKunActivity.this, res);
//            mediaPlayer.start();
//        }
        if (spool!=null) {
            spool.play(res, 1, 1, 1, 0, 1);
        }
    }

    /**
     * 初始化音乐播放器
     */
    // @TargetApi(Build.VERSION_CODES.L)
    private void initSoundpool() {
        //Sdk版本>=21时使用下面的方法
        if(Build.VERSION.SDK_INT>=21){
            SoundPool.Builder builder=new SoundPool.Builder();
            //设置最多容纳的流数
            builder.setMaxStreams(1);
            AudioAttributes.Builder attrBuilder=new AudioAttributes.Builder();
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            spool=builder.build();
        }else{

            spool=new SoundPool(1,AudioManager.STREAM_MUSIC, 0);


        }
        //加载音频文件，返回音频文件的id
        id_tap=spool.load(getApplicationContext(),R.raw.music_tap,1);
        id_err=spool.load(getApplicationContext(),R.raw.music_err,1);
        id_end=spool.load(getApplicationContext(),R.raw.music_end,1);
    }

    /**
     * 生成坤坤坐标 集合
     */
    private void initData() {
        arrayList = new ArrayList<>();
        Random rand = new Random();
        for (int i = 1; i <=400; i++) {
            int random= rand.nextInt(4)+1;
            if (i%4==0) {
                arrayList.add(i-random,i);
            }else {
                arrayList.add(i);
            }
        }
    }
}